package com.hjh.core.service

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.elvishew.xlog.XLog
import com.hjh.res.R
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import java.lang.ref.WeakReference

/**
 * @author： hjh
 * @createDate： 2025/2/6 14:04
 * @description：前台服务保活 + 通知
 * @note：参考 lib-base 模块下 AndroidManifest.xml 定义 service
 * @qq： 3472903821
 * @version: 1.0
 */
open class BaseForegroundService : Service() {

    protected val serviceScope = CoroutineScope(
        SupervisorJob() +
                Dispatchers.IO +
                CoroutineExceptionHandler { _, e ->
                    XLog.tag(this.javaClass.simpleName).e("Coroutine failed", e)
                }
    )

    override fun onCreate() {
        super.onCreate()
        setInstance(this)
        XLog.d("${this.javaClass.simpleName} 已启动")
        init()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 如果 action 为 stopAction，停止服务
        if (intent?.action == stopAction) {
            XLog.i("${this.javaClass.simpleName} 关闭中")
            stop() // 停止相关服务
            stopSelf() // 停止当前服务，并移除前台通知
            return START_NOT_STICKY // 服务不重新启动
        }

        intent?.action?.let {
            onAction(it) // 处理 Action
        }

        start() // 拉起服务
        return START_STICKY // 服务被杀死后重启
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        stop() // 停止相关服务
        super.onTaskRemoved(rootIntent)
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onDestroy() {
        stop() // 停止相关服务
        super.onDestroy()
        serviceScope.cancel()
    }

    /**
     * 开启前台通知
     */
    @SuppressLint("ObsoleteSdkInt")
    protected fun startForegroundNotification(
        channelId: String = "通道ID",
        channelName: String = "通道名称",
        title: String = "通知标题",
        content: String = "通知内容",
        close: Boolean = false,
        closeText: String = "关闭"
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                channelName,
                NotificationManager.IMPORTANCE_LOW
            )
            val notificationManager = this.getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }

        // 创建停止服务的 PendingIntent
        val stopServiceIntent = Intent(this, BaseForegroundService::class.java)
        stopServiceIntent.action = stopAction
        val pendingIntentFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        } else {
            PendingIntent.FLAG_UPDATE_CURRENT
        }
        val stopServicePendingIntent: PendingIntent = PendingIntent.getService(
            this, 0, stopServiceIntent, pendingIntentFlag
        )

        val notification: Notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle(title)
            .setContentText(content)
            .setSmallIcon(R.drawable.ic_backend)
            .apply {
                if (close) {
                    addAction(
                        android.R.drawable.ic_delete, // 关闭按钮的图标
                        closeText,
                        stopServicePendingIntent // 绑定点击事件
                    )
                }
            }
            .setOngoing(true)  // 设置为正在进行，点击后不能移除通知
            .build()

        startForeground(1, notification)
    }

    /**
     * 初始化
     */
    protected open fun init() {}

    /**
     * 服务启动
     */
    protected open fun start() {}

    /**
     * 服务通知
     */
    protected open fun stop() {}

    /**
     * 处理 Action
     */
    protected open fun onAction(action: String) {}

    companion object {

        private var stopAction = "STOP_SERVER"
        private var baseForegroundServiceRef: WeakReference<BaseForegroundService>? = null

        @SuppressLint("ObsoleteSdkInt")
        fun startService(context: Context, clazz: Class<*>, action: String? = null) {
            val intent = Intent(context, clazz).apply {
                action?.let {
                    this.action = it
                }
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }

        fun stopService(context: Context, clazz: Class<*>, action: String? = null) {
            val intent = Intent(context, clazz).apply {
                action?.let {
                    this.action = it
                }
            }
            context.stopService(intent)
        }

        fun setInstance(instance: BaseForegroundService) {
            baseForegroundServiceRef = WeakReference(instance)
        }

        fun getInstance(): BaseForegroundService? {
            return baseForegroundServiceRef?.get()
        }

        fun setStopAction(action: String) {
            this.stopAction = action
        }
    }
}